import * as Api from '../../api/plan/planViewApi';
import { observable, action, toJS } from 'mobx';
import { BrowserHrmCondition,RouteLayout, Reply, BrowserHrm, Upload, TreePage, ListEditable, CKRichText, ListViewPage } from 'weaver-mobile-page';
import { Toast, Tools, Bubble } from 'weaver-mobile'
import * as util from '../../util';
import { buildCondition } from '../../components/plan/coms'
const getLabel = Tools.getLabel;
export default class PlanViewStore {
  @observable data = {};
  //basic
  @observable resourcename = '';
  @observable resourceid = '';
  @observable enddate = '';
  @observable isLoading = false;
  @observable userLanguage = ''
  @observable scrollHeight = 0 //滚动条位置

  @observable year = new Date().getFullYear()
  @observable type1 = ''
  @observable type2 = ''
  @observable errorMsg = ''
  @observable weekList = []
  @observable weekText = ''
  @observable totalWeek = 55
  //所用模板
  @observable programid = ''
  @observable category = ''
  //文件
  @observable files = []
  //周报月报
  @observable tabDatas = [];

  //计划属性
  @observable planid = ''
  @observable planname = ''
  @observable planstatus = ''
  @observable urlPlanId = ''
  //操作日志
  @observable logStore = new ListViewPage.Store({ route: '/planHome/planView/log' });
  @observable planLog = {
    planid: '',
    datas: [],
    lastcount: 0,
    lastid: '',
    status: '',
    logType: 'all',
  };
  //意见反馈
  @observable fblist = []
  @observable fbReply = new Reply.Store();
  //说明
  @observable remark = ''
  @observable remarkLayout = new RouteLayout.Store({ route: '/planHome/planView/index' });
  @observable remarkStore = new CKRichText.Store(
    {
      reply: {
        getAttachList: this.getReplyAttachList,
      }
    }
    );

  //文件
  @observable fileids = ''
  @observable fileStore = new Upload.Store({ route: '/planHome/planView/index' });
  @observable maxsize = 0
  //planMap
  @observable planmap = [];
  @observable planlist = [];
  //summarymap
  @observable summarymap = [];
  @observable summaryin = []
  @observable summaryout = []

  //detail 
  @observable detailLayoutStore = new RouteLayout.Store({ route: '/planHome/planView/index', id: 'detail' });
  @observable detailFileStore = new Upload.Store({ route: '/planHome/planView/index/detail' });
  @observable detailMapData = {}
  @observable detailMapList = []
  @observable detailId = ''
  @observable detailFileIds = ''
  @observable detailFiles = []
  //共享
  @observable browserShare = new BrowserHrm.Store({ route: '/planHome/planView/share', id: 'shareHrm' });
  @observable shareids = ''
  @observable browserShareValue = [];

  //auth
  @observable canedit = false
  @observable canaudit = false
  @observable candel = false
  @observable canreset = false
  @observable canshare = false

  //审批
  @observable auditList = []

  //组织树
  @observable orgTreeStore = new TreePage.Store({ route: '/planHome/planView/org' });

  //新建
  @observable newLayoutStore = new RouteLayout.Store({ route: '/planHome/planView/index', id: 'new' });

  //可编辑列表
  @observable planListStore = new ListEditable.Store({ route: '/planHome/planView/index' });
  @observable summaryInStore = new ListEditable.Store({ route: '/planHome/planView/index' });
  @observable summaryOutStore = new ListEditable.Store({ route: '/planHome/planView/index' });
  @observable planConditions = [];
  @observable summaryConditions = [];

  //绩效开启
  @observable isperformance

  //共享
  @observable shareStore = new BrowserHrmCondition.Store({ route: '/planHome/planView/share', id: 'shareHrm' });
  @observable shareStoreValue = [];

  getReplyAttachList = () => {
    const browserConfig = {
      type: 'browser',
      path: `${this.path}/browser`,
      model: 1, // model(模式) 1: 常规模式， 2: 编辑模式（不显示小红点）
    };
    const attachList = [

    ];
    return new Promise(resolve => resolve({ attachList }));
  }
  @observable statusValue = {
    "-1": getLabel('508873', '无数据'),
    "0": getLabel('220', '草稿'),
    "1": getLabel('19134', '审批中'),
    "2": getLabel('236', '退回'),
    "3": getLabel('23774', '已完成'),
    "4": getLabel('1979', '未开始'),
    "6": getLabel('382750', '已过期'),
    "7": getLabel('508873', '无数据'),
  }

  @action setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  };

  //获取报告
  @action getPlanView = () => {
    Toast.loading('loading', 0)
    this.isLoading = true
    let params = {
      year: this.year,
      type1: this.type1,
      type2: this.type2,
      resourceid: this.resourceid,
      planid: this.urlPlanId
    }
    Api.getPlanView(params).then(res => {
      Toast.hide()
      this.isLoading = false
      this.resourceid = res.resourceid
      this.resourcename = res.resourcename
      this.year = res.year
      this.type1 = res.type1
      this.type2 = res.type2
      this.planid = res.planid;
      this.planname = res.planname == '' ? this.getPlanName(res.resourcename) : res.planname
      this.planstatus = res.planstatus ? res.planstatus : ''
      this.enddate = res.enddate
      
      //auth
      this.canedit = res.canedit
      this.canreset = res.canreset
      this.candel = res.candel
      this.canaudit = res.canaudit
      this.canshare = res.editshare
      this.maxsize = res.maxsize ? res.maxsize : 0
      this.category = res.category
      this.tabDatas = res.tabDatas
      this.auditList = res.auditList ? res.auditList : []
      this.isperformance = res.isperformance
      this.userLanguage = res.userLanguage
      this.scrollHeight =0
      this.planLog={
        planid: '',
        datas: [],
        lastcount: 0,
        lastid: '',
        status: '',
        logType: 'all',
      };
      this.logStore.clearData()
      this.browserShareValue=[]
      this.shareids = ''
      document.getElementsByClassName("cr-back-top-title")[0].style.display = "none";
      this.isshowsummary = res.isshowsummary?res.isshowsummary:true
      this.isshowplan = res.isshowplan?res.isshowplan:true
      if (res.api_status == '1') {
        this.planmap = res.planmap;
        this.planlist = res.planlist;
        this.summarymap = res.summarymap;
        this.summaryin = res.summaryin ? res.summaryin : []
        this.summaryout = res.summaryout ? res.summaryout : []

        this.files = util.formatFiles(res.filearry, this.canedit)
        this.fileids = res.fileids?res.fileids:''
        this.programid = res.programid
        this.remark = res.remark
        this.fblist = res.fblist
        this.browserShareValue = res.shareidsList ?res.shareidsList:[]

        this.errorMsg = ''
        this.getPlanLog(true);

        this.summaryConditions = this.getPlanViewNewCondition(res.summarymap.list)
        this.planConditions = this.getPlanViewNewCondition(res.planmap.list)
        // this.getPlanViewNewCondition({
        //   mapList:JSON.stringify(res.summarymap.list)
        // })
        // this.getPlanViewNewCondition({
        //   mapList:JSON.stringify(res.planmap.list)
        // })
      } else {
        this.errorMsg = res.api_status
      }
    }).catch(res => {
      Bubble.error(getLabel('508818', '接口调用失败！'), 3, null, null, null, false);
      Toast.hide()
    });
  };


  //删除报告
  @action deletePlanView = (operation) => {
    let params = {
      planid: this.planid,
      year: this.year,
      type1: this.type1,
      type2: this.type2,
      resourceid: this.resourceid
    }
    return Api.deletePlanView(params).then(res => {
      if (res.api_status == '1') {
    //    this.getPlanView()
      }
      return res
    });
  }


  //重置报告
  @action resetPlan = (operation) => {
    let params = {
      planid: this.planid
    }
    Api.resetPlan(params).then(res => {
      if (res.api_status == '1') {
        this.getPlanView()
      }
    });
  }


  //保存报告
  @action saveOrSumbit = (operation,showToast) => {
    let params = this.getPlanViewParams(operation)
    Toast.loading('loading', 0)
    Api.saveOrSubmitPlan(params).then(res => {
      if (res.api_status == '1') {
        showToast && Bubble.success(getLabel('30700', '操作成功'), 3);
        showToast && this.getPlanView()
      }
      Toast.hide()
    });
  }

  //获取报告参数
  getPlanViewParams = (operation) => {
    let summaryin = toJS(this.summaryin)
    let summaryout = toJS(this.summaryout)
    let planlist = toJS(this.planlist)
    this.removeFieldsNoInColumns(summaryin)
    this.removeFieldsNoInColumns(summaryout)
    this.removeFieldsNoInColumns(planlist)
    let params = {
      resourceid: this.resourceid,
      planid: this.planid,
      operation,
      planname: this.planname,
      year: this.year,
      type1: this.type1,
      type2: this.type2,
      remark: this.remark,
      fileids: this.fileids,
      programid: this.programid,
      summaryin: JSON.stringify(summaryin),
      summaryout: JSON.stringify(summaryout),
      planlist: JSON.stringify(planlist),
    }
    return params
  }
  //去掉无用的属性
  removeFieldsNoInColumns(data) {
    if (data && data.length > 0) {
      data = data.map(v => {
        delete v['fbdate'];
        delete v['taskarray']
        delete v['filearray']
        delete v['docarray']
        delete v['wfarray']
        delete v['crmarray']
        delete v['projectarray']
        if (v.id && (v.id.startsWith('temp') || v.id.indexOf("_") > -1)) {
          delete v['id'];
        }
        return v;
      });
    }
  }

  //设置工作计划标题
  getPlanName = (resourcename) => {
    //杨文元2019年28周工作总结及2019年29周工作计划
    let year = this.year
    let month = this.type2
    let week = this.type2
    let nextYear = month == 12 ? parseInt(year) + 1 : year;
    let nextMonth = month == 12 ? 1 : (parseInt(month) + 1);
    let monthOrWeekValue = this.type1 == '1' ? month + '月' : week + '周'
    let nextMonthOrWeekValue = this.type1 == '1' ? nextMonth + '月' : parseInt(week) + 1 + '周'

    let planname = ''
    if (this.userLanguage == "8") {
      monthOrWeekValue = this.type1 == '1' ? "month " + month : "week " + week
      nextMonthOrWeekValue = this.type1 == '1' ? "month " + nextMonth : "week " + parseInt(week) + 1
      planname = `${resourcename}${year}-${monthOrWeekValue} work summary and ${nextYear}-${nextMonthOrWeekValue} work plan`
    } else {
      planname = `${resourcename}${year}年${monthOrWeekValue}工作总结及${nextYear}年${nextMonthOrWeekValue}工作计划`
    }

    return planname;
  };

  //获取报告操作日志
  @action getPlanLog = (isReset = true) => {
    this.planLog.planid = this.planid;
    const {logType,lastid,lastcount,planid} = this.planLog
    let parmas= {
      logType,lastid,lastcount,planid
    }
    Api.getPlanLog(parmas).then(res => {
      if (res.api_status == '1') {
        let tempArray = toJS(this.planLog.datas);
        if(tempArray && res.datas){
          tempArray.push(...res.datas);
        }
        this.planLog = res;
        this.planLog.datas = tempArray;

        

        const newState = {
          isTable: false,
          loading: false,
          haveCheck: false,
          template: { default: [] },
          hasMore: res.lastcount > 0 ,
          data: res.datas && isReset?res.datas: this.logStore.data.concat(res.datas),
        };
        this.logStore.setState(newState);
        this.logStore.updateDataSource();

      }
    });
  };

  //获取报告详情
  @action getDetailView = (params) => {
    Toast.loading('loading', 0)
    return Api.getDetailView(params).then(res => {
      Toast.hide()
      if (res.api_status == '1') {
        this.detailMapData = res.mapdata
        this.detailMapList = res.customList
        this.detailId = res.plandetailid
        if (res.mapdata && res.mapdata.filearray) {
          this.detailFiles = util.formatFiles(res.mapdata.filearray, this.canedit)
        }
        this.detailFileIds = res.mapdata.fileids

        //   this.props.history.push({pathname :'planHome/detail'})
      }
      return res
    });
  }
  //保存报告详情
  @action saveDetailView = (params,showToast) => {
    Toast.loading('loading', 0)
    return Api.saveDetailView(params).then(res => {
      if (res.api_status == '1') {
        showToast && Bubble.success(getLabel('30700', '操作成功'), 3);
      } else {

      }
      Toast.hide()
      return res
    });
  }
  //保存意见反馈
  @action saveFeedback = (text) => {
    Toast.loading('loading', 0)
    return Api.saveFeedback({ planid: this.planid, content: text }).then(res => {
      if (res.api_status == '1') {
        let list = toJS(this.fblist)
        list.unshift(res.datas)
        this.setState({ fblist: list })

        this.fbReply.doClear()
      }
      Toast.hide()
      return res
    });
  }
  //设置共享
  @action setPlanShare = (text) => {
    Toast.loading('loading', 0)
    let params = { planid: this.planid, shareids: this.shareids }
    return Api.setPlanShare(params).then(res => {
      if (res.api_status == '1') {

      }
      Toast.hide()
      return res
    });
  }
  //新版共享
  @action setShare = (text) => {
    Toast.loading('loading', 0)
    let params = { workrelatetype:4,
      bizid:this.planid,
      resourceid: this.resourceid,
      operate:'mobileChange',
      data:JSON.stringify(this.shareStoreValue)
    }
    return Api.setShare(params).then(res => {
      if (res.api_status == '1') {

      }
      Toast.hide()
      return res
    });
  }
  //查询共享
  @action getShare = (text) => {
    Toast.loading('loading', 0)
    let params = { workrelatetype:4,
      bizid:this.planid,
      resourceid: this.resourceid,
      operate:'mobileSearch'
    }
    return Api.setShare(params).then(res => {
      if (res.status) {
        this.shareStoreValue = res.data
      }
      Toast.hide()
      return res
    });
  }


  //获取新建条件参数
  getPlanViewNewCondition = (list) => {
    let conditions = []
    list.map(m => {
      conditions.push(buildCondition(m.inputtype, m.fieldname, m.showname, m.ismust))
    })
    return conditions
  }
  //getweek
  @action getWeek = (params = {}) => {
    // Toast.loading('loading',0)
    return Api.getWeek(params).then(res => {
      this.weekList = res.datas
      this.weekText = res.currentdates
      this.totalWeek = res.totalWeek
      return res
    });
  }
  //新建任务
  @action addTask = (name, detailid, begindate, enddate) => {
    let params = {
      taskName: name,
      principalid: this.resourceid,
      begindate,
      enddate,
      plandetailid: detailid
    }

    Toast.loading('loading', 0)
    return Api.addTask(params).then(res => {
      if (res.api_status) {
        Bubble.success(getLabel('30700', '操作成功'), 3);
        this.saveOrSumbit("save")
      }
      Toast.hide()
      return res
    });
  }
  //审批
  @action auditPlan = (operation, planid) => {
    let params = {
      operation, planid
    }
    Toast.loading('loading', 0)
    return Api.auditSingle(params).then(res => {
      if (res.api_status) {
        Bubble.success(getLabel('30700', '操作成功'), 3);
        if (window.refreshPlanAuditNum && typeof window.refreshPlanAuditNum === "function") {
            window.refreshPlanAuditNum();
        }
        this.getPlanView()
      }
      Toast.hide()
      return res
    });
  }
  //首页滚动条位置记录
  recordIndexScrollHeight = () => {
    if (document.getElementsByClassName("workrelate-mobile-plan-planview-content")[0]) {
      this.scrollHeight = document.getElementsByClassName("workrelate-mobile-plan-planview-content")[0].scrollTop
    }
  }
  //首页跳转到指定位置
  scrollIndex2Height = () => {
    setTimeout(() => {
      if (document.getElementsByClassName("workrelate-mobile-plan-planview-content")[0]) {
        document.getElementsByClassName("workrelate-mobile-plan-planview-content")[0].scrollTop = this.scrollHeight
      }
    }, 200)
  }
}


